<script lang="js" setup>
import { onMounted, onUnmounted, ref } from 'vue';
import { getQrCode , checkQrCodeStatus } from '@/api/wechat';
import { useUserStore } from '@/store/useUserStore';

const userStore = useUserStore();
const qrCodeSrc = ref('');     // 二维码图片地址
const isLoading = ref(true);   // 加载状态
const state=ref('')            //二维码标识
const status = ref('pending'); // 扫码状态：pending/confirmed/expired
let timer = null; // 定时器
// 声明已登录事件
const emit=defineEmits(['closeQrCode'])
//获取二维码
const getQrLoginCode=async()=>{
  try{
    //加载状态开启
    isLoading.value = true;
    console.log('获取二维码');
    //获取二维码和二维码标识
    const data = await getQrCode();
    qrCodeSrc.value = data.image;
    state.value = data.state;
    //开始轮询检查二维码状态
    checkStatus();
  }catch(err){
    console.log(err);
  }finally{
    isLoading.value = false;
  }
}

//轮询检查二维码状态
const checkStatus=()=>{
  //清除之前的定时器
  clearTimer();
  //开启定时器
  timer= setInterval(async()=>{
    try{
      //通过二维码标识，返回二维码状态
      const data = await checkQrCodeStatus(state.value);
      status.value = data.status;
      console.log(data)
      // 根据状态处理
      switch (status.value) {
        // 已确认
        case 'confirmed':
          console.log(data);
          //用户信息存入localStorage
          // const userData=data.userInfo;
          localStorage.setItem('userInfo', JSON.stringify(data.userInfo));
          localStorage.setItem('token', data.token);
          userStore.setUserInfo(data.userInfo);
          userStore.setToken(data.token);
          console.log('扫码获取的用户信息', userStore.userInfo);
          clearTimer();
          break;
        case 'expired':
          // 已过期，停止轮询
          clearInterval(timer);
          timer = null;
          break;
        default:
        // pending状态继续轮询
      }
    }catch(err){
    console.log(err);
    clearTimer();
  }
  },3000);
}

//刷新二维码
const refreshQrCode=()=>{
  isLoading.value = true;
  //清除之前的定时器
  clearTimer();
  qrCodeSrc.value = '';
  state.value = '';
  status.value = 'pending';
  getQrLoginCode();
}

const clearTimer=()=>{
  if(timer){
    clearInterval(timer);
    timer = null;
  }
}

//关闭二维码
const closeQrCode=()=>{
  clearTimer();
  qrCodeSrc.value = '';
  state.value = '';
  status.value = 'pending';
  emit('closeQrCode');
}

//挂载时请求
onMounted(()=>{
  getQrLoginCode();
})

onUnmounted(()=>{
  clearTimer();
})



</script>
<template>
  <div class="wechat-login-page" >
    <div class="cancel-btn" @click="closeQrCode"></div>
    <div class="login-container">
        <h2>微信登录</h2>
        <p v-if="status==='pending'">请使用微信扫描二维码登录</p>
        <p v-else-if="status==='confirmed'">登录成功</p>
        <p v-else-if="status==='expired'">二维码已过期</p>
        <!-- 二维码展示区域 -->
        <div class="qrcode-container">
          <div v-if="isLoading" class="loading">加载中...</div>
          <!-- 待扫码状态 -->
          <img v-else-if="qrCodeSrc && status === 'pending'" 
             :src="qrCodeSrc" 
             alt="二维码" 
             class="qrcode-img">
          <!-- 扫码成功状态 -->
          <div v-else-if="status==='confirmed'" class="login-success">正在登录...</div>
          <!-- 二维码过期状态 -->
           <div v-else-if="status==='expired'" class="qrcode-expired">
              <p class="error-text">二维码加载失败或已过期</p>
              <button @click="refreshQrCode" class="refresh-btn">重新获取</button>
            </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
.wechat-login-page{
  width: 300px;
  height: 350px;
  background-color: white;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  box-shadow: (0 2px 8px rgba(0,0,0,0.1));
}
.cancel-btn{
  width: 32px;
  height: 32px;
  position: absolute;
  top:20px;
  right: 10px;
  cursor: pointer;
  background: url(https://s1.hdslb.com/bfs/seed/jinkela/short/mini-login-v2/img/close.a35a1809.svg) no-repeat;
  background-size: 100% 100%;
  z-index: 2;
}
.login-container{
  width: 90%;
  height: 90%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 10px;
  
}
.qrcode-container{
  width: 200px;
  height: 200px;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
}
.qrcode-img {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  display: block;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 8px;
}
.qrcode-expired{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20px;

}
</style>